#include "cmainwindow.h"
#include "ctitlebar.h"
#include "qss.h"
#include <windows.h>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QKeyEvent>
#include <QWidget>
#include <QDebug>
#include <QMenu>
#include <QPushButton>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QShortcut>
#include <string>
using namespace std;

// 处理bug，
// bug: 当鼠标移动到播放视频的窗口中时，会自动消失，且无法再响应鼠标的双击操作，从而导致鼠标双击操作失效
BOOL CALLBACK EnumVLC(HWND hwnd, LPARAM lParam)
{
    TCHAR szTitle[1024];

    int nLen = GetWindowText(hwnd, szTitle, 1024);

    if (nLen > 0)
    {
        // 启用或者禁用鼠标和键盘对指定窗口或控件的输入。
        // 禁用输入时，窗口不会接收鼠标单击和按键等输入；
        // 启用输入时，窗口将接收所有输入
        qDebug() << "98-------" << endl;
        EnableWindow(hwnd, FALSE);
        KillTimer(NULL, 1);
    }

    return TRUE;
}

void CALLBACK TimeProc(HWND hwnd, UINT msg, UINT_PTR id, DWORD time)
{
    HWND vlcHwnd = FindWindowEx(NULL, NULL, NULL, L"cmw");

    if (vlcHwnd)
    {
        //qDebug() << "111-------" << endl;
        EnumChildWindows(vlcHwnd, EnumVLC, NULL);
    }
}

CMainWindow::CMainWindow(QWidget * parent)
    : CFramelessWidget(parent)
{

    // 启用鼠标移动事件追踪
    setMouseTracking(true);
    setWindowTitle("cmw");
    resize(1000, 800);
    //this->setAttribute(Qt::WA_StyledBackground);
    initUI();

}

void CMainWindow::closeSlot()
{
    QMessageBox::StandardButton isExit = QMessageBox::warning(this, "提示", "你确定要退出吗？",
            QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    if(isExit == QMessageBox::Yes) {
        close();
    }
}

void CMainWindow::initUI()
{
    /*-----菜单栏-----*/
    QMenu * fileMenuItems = new QMenu;
    fileMenuItems->setIcon(QIcon(":/resources/file.png"));
    fileMenuItems->setTitle("文件");

    QList<QAction *> fileAcList;
    QAction * openFileAc = new QAction(QIcon(":/resources/file.png"), "打开文件", this);
    openFileAc->setShortcut(QKeySequence("Ctrl+8"));// 设置快捷键

    QAction * openFolderAc = new QAction("打开文件夹", this);
    QAction * openUrlAc = new QAction("打开url", this);
    fileAcList << openFileAc << openFolderAc << openUrlAc;
    fileMenuItems->addActions(fileAcList);//添加二级子菜单

    QMenu *menu = new QMenu;//主菜单
    menu->addMenu(fileMenuItems);//添加一级子菜单

    QAction * playAc = new QAction(QIcon(":/resources/play.png"), "播放", this);
    QAction * toolsAc = new QAction(QIcon(":/resources/tools.png"), "工具", this);
    menu->addAction(playAc);
    menu->addAction(toolsAc);
    menu->addSeparator();//添加分隔线

    QMenu * setMenuItems = new QMenu;
    setMenuItems->setTitle("设置");
    setMenuItems->setIcon(QIcon(":/resources/set.png"));

    QList<QAction*> setAcList;
    QAction * sysSetAc = new QAction("系统设置", this);
    QAction * playSetAc = new QAction("播放设置", this);
    QAction * captionSetAc = new QAction("字幕设置", this);
    setAcList << sysSetAc << playSetAc << captionSetAc;
    setMenuItems->addActions(setAcList);
    menu->addMenu(setMenuItems);

    menu->addSeparator();//添加分隔线

    QAction * exitAc = new QAction(QIcon(":/resources/exit.png"), "退出", this);
    menu->addAction(exitAc);

    //设置样式表
    string menu_qss = R"(
        QMenu::item
        {
             font:16px;
             background-color:rgb(25,253,253);
             padding:8px 32px;
             margin:28px 8px;
             border-bottom:1px solid #FF0000;
        }

        /*选择项设置*/
        QMenu::item:selected
        {
             background-color: #00FF00;
        }
    )";
    menu->setStyleSheet(QString::fromStdString(menu_qss));




    /*-----底部栏-----*/
    //VLC
    _vlcKits = new VLCKits();

    //播放界面
    _cVideoWidget = new CVideoWidget(this);
    _cVideoWidget->setStyleSheet("background-color: black;");
    _cVideoWidget->getMenu(menu);

    //进度条
    _hSlider = new CProgressBar();


    //底部栏
    _cbcb = new CBottomCtrlBar();
    _cbcb->showTimeLabel(true);

    _playbtn = _cbcb->getcplaybtn();
    _playbtn->setVLC(_vlcKits);




    /*-----标题-----*/
    _ptitleBar = new CTitleBar(this);




    /*-----菜单栏-----*/
    QPushButton *btMenu = new QPushButton(_ptitleBar);

    btMenu->move(42, 0);

    btMenu->setMenu(menu);//在按钮上设置菜单

    btMenu->setText("卷饼影音");

    btMenu->setStyleSheet(
            "QLabel{font-family: Microsoft YaHei;"
            "font-size:18px;"
            "color:#BDC8E2;background-color:rgb(54,54,54);}");
    btMenu->setFixedSize(120, 42);
    btMenu->setMenu(menu);//在按钮上设置菜单

    btMenu->setStyleSheet(QString::fromStdString(buttonQss));
    menu->setStyleSheet(QString::fromStdString(menuQss));//设置样式表
    fileMenuItems->setStyleSheet(QString::fromStdString(menuItemQss));//设置样式表
    setMenuItems->setStyleSheet(QString::fromStdString(menuItemQss));//设置样式表





    /*-----播放列表-----*/
    _playlistwidget = new CPlayList(this);
    _list = _playlistwidget->getList();


    /*-----空格关联暂停/播放-----*/
    QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_Space), this);
    connect(shortcut, &QShortcut::activated, this, &CMainWindow::play_pause);




    /*-----布局-----*/

    // 新增水平布局（视频+播放列表）
    QHBoxLayout *mediaLayout = new QHBoxLayout(this);
    mediaLayout->setContentsMargins(0, 0, 0, 0);

    QVBoxLayout *Layout = new QVBoxLayout();
    Layout->setContentsMargins(0, 0, 0, 0);

    Layout->setSpacing(0); // 设置间距为0
    Layout->addWidget(_ptitleBar);

    Layout->setSpacing(0); // 设置间距为0
    Layout->addWidget(_cVideoWidget);

    Layout->setSpacing(0); // 设置间距为0
    Layout->addWidget(_hSlider);
    Layout->setSpacing(0); // 设置间距为0
    Layout->addWidget(_cbcb);

    mediaLayout->addLayout(Layout);// 将水平布局加入主布局
    mediaLayout->setSpacing(0);
    mediaLayout->addWidget(_playlistwidget);// 右侧播放列表

    setLayout(mediaLayout);



    /*-----中间按钮-----*/
    _btMenuCenter = new QPushButton(_cVideoWidget);

    _btMenuCenter->setFixedSize(120, 42);

    QHBoxLayout *centerLayout = new QHBoxLayout(_cVideoWidget);
    centerLayout->setContentsMargins(0, 0, 0, 0);
    centerLayout->setAlignment(Qt::AlignCenter);
    centerLayout->addWidget(_btMenuCenter);

    _cVideoWidget->setLayout(centerLayout);

    _btMenuCenter->setMenu(menu);//在按钮上设置菜单

    _btMenuCenter->setText("卷饼影音");
    _btMenuCenter->setMenu(menu);//在按钮上设置菜单

    _btMenuCenter->setStyleSheet(QString::fromStdString(buttonQss));
    menu->setStyleSheet(QString::fromStdString(menuQss));//设置样式表
    fileMenuItems->setStyleSheet(QString::fromStdString(menuItemQss));//设置样式表
    setMenuItems->setStyleSheet(QString::fromStdString(menuItemQss));//设置样式表


    /*-----信号和槽-----*/

    //菜单打开文件
    connect(openFileAc, &QAction::triggered, this, &CMainWindow::on_btnOpen_clicked);
    //菜单播放
    connect(playAc, &QAction::triggered, this, &CMainWindow::play_pause);
    //菜单退出
    connect(exitAc, &QAction::triggered, this, &CMainWindow::closeSlot);

    //title关闭
    connect(_ptitleBar, &CTitleBar::sigClose, this, &CMainWindow::closeSlot);
    connect(_ptitleBar, &CTitleBar::sigTitleFull, this, &CMainWindow::titleDoubleClickEvent);

    //底部栏
    //播放、暂停
    connect(_cbcb, &CBottomCtrlBar::sig_play, this, &CMainWindow::play_pause);
    connect(_cVideoWidget, &CVideoWidget::play_pause, this, &CMainWindow::play_pause);
    //停止
    connect(_cbcb, &CBottomCtrlBar::sig_stop, this, &CMainWindow::on_btnStop_clicked);
    //全屏缩放
    connect(_cbcb, &CBottomCtrlBar::sig_fullScreen, this, &CMainWindow::fullScreen);

    //时间标签
    connect(_vlcKits, &VLCKits::sigCurPlay, this, &CMainWindow::setCurPlayTime);
    connect(_vlcKits, &VLCKits::sigTotal, this, &CMainWindow::setTotalTime);

    //进度条
    connect(_vlcKits, &VLCKits::sigTimeSliderPos, this, &CMainWindow::setTimeSliderValue);
    connect(_hSlider, &QSlider::sliderMoved, _vlcKits, &VLCKits::setPosition);

    //播放列表的显示/隐藏
    connect(_playlistwidget, &CPlayList::closelist, this, &CMainWindow::list);
    connect(_cbcb, &CBottomCtrlBar::sig_list, this, &CMainWindow::list);
    connect(_playlistwidget, &CPlayList::playlist, this, &CMainWindow::onPlaylistItemClicked);

    connect(_vlcKits, &VLCKits::updateCurrentFileShow, _playlistwidget, &CPlayList::updateCurrentPlayingItem);

    //获得当前播放下标

    connect(_vlcKits, &VLCKits::updateCurrentFileShow, this, &CMainWindow::setCurrIdx);

    //播放上一个/下一个
    connect(_playbtn, &CPlayButtonGroupWidget::sig_next, this, &CMainWindow::playNext);
    connect(_playbtn, &CPlayButtonGroupWidget::sig_pre, this, &CMainWindow::playPre);

    connect(_cVideoWidget, &CVideoWidget::move, this, &CMainWindow::videoWidgetMoveEvent);


    SetTimer(NULL, 1, 300, TimeProc);
}

void CMainWindow::list()
{
    if(!this->isFullScreen()){
        //播放列表的显示/隐藏不应该影响左侧布局的大小
        if(_playlistwidget->isVisible()){
            //显示变为隐藏
            resize(width()-_playlistwidget->width(), height());
        }else{
            resize(width()+_playlistwidget->width(), height());
        }
    }
    _playlistwidget->setVisible(!_playlistwidget->isVisible());
}

void CMainWindow::titleDoubleClickEvent()
{
    if (this->isFullScreen())
    {
        this->showNormal();
        resize(1000, 800);
        if(_playlistwidget->isVisible()){
            resize(width()+_playlistwidget->width(), height());
        }
        showWidget();
        _ptitleBar->updateMaxButtonIcon(false);
    }
    else
    {
        this->showFullScreen();
        //hideWidget();
        _ptitleBar->updateMaxButtonIcon(true);
    }
}

void CMainWindow::keyPressEvent(QKeyEvent* event)
{
    if (event->key() == Qt::Key_Escape)
    {
        if (this->isFullScreen())
        {
            this->showNormal();
            resize(1000, 800);
            if(_playlistwidget->isVisible()){
                resize(width()+_playlistwidget->width(), height());
            }
            showWidget();
            _ptitleBar->updateMaxButtonIcon(false);
        }
    }

    //回车键,全屏，非全屏
    else if(event->key()==Qt::Key_Enter||event->key()==Qt::Key_Return){
        fullScreen();
    }
    else if (event->key() == Qt::Key_Space)
    {
        play_pause();
        event->accept();
    }
    return CFramelessWidget::keyPressEvent(event);
}

void CMainWindow::videoWidgetMoveEvent()
{
    qDebug() << "鼠标移动" ;
    lastMouseMoveTime = QDateTime::currentDateTime();

    showWidget();
    if (isFullScreen() && !_isRunning) {
        _timerId = startTimer(200);  // 每秒检测一次
        _isRunning = true;
    }
}

void CMainWindow::mouseMoveEvent(QMouseEvent* event)
{
    qDebug() << "鼠标移动" ;
    lastMouseMoveTime = QDateTime::currentDateTime();

    showWidget();
    if (isFullScreen() && !_isRunning) {
        _timerId = startTimer(200);  // 每秒检测一次
        _isRunning = true;
    }
}

void CMainWindow::timerEvent(QTimerEvent *event)
{
    qint64 elapsed = lastMouseMoveTime.msecsTo(QDateTime::currentDateTime());
    if (elapsed > 3000) {
        hideWidget();
        killTimer(_timerId);
        _isRunning = false;
    }
    return CFramelessWidget::timerEvent(event);

}

//void CMainWindow::contextMenuEvent(QContextMenuEvent *event)
//{
//    // 显示菜单（鼠标位置）
//    menu->exec(event->globalPos());  // ✔️ 使用事件坐标精准定位
//    return CFramelessWidget::contextMenuEvent(event);
//}

void CMainWindow::hideWidget()
{
    _ptitleBar->hide();
    _hSlider->hide();
    _cbcb->hide();
}

void CMainWindow::showWidget()
{
    _ptitleBar->show();
    _hSlider->show();
    _cbcb->show();
}

void CMainWindow::on_btnOpen_clicked()
{

    QFileDialog dialog(this);
    dialog.setFileMode(QFileDialog::ExistingFiles);  // 允许多选
    dialog.setNameFilter(tr("视频文件 (*.mp4 *.avi);;所有文件 (*)"));
    dialog.setViewMode(QFileDialog::Detail);         // 显示详细视图
    dialog.setDirectory("D:/qt/qtProject/videos");                // 设置初始目录
    if (dialog.exec() == QDialog::Accepted) {
        QStringList filePaths = dialog.selectedFiles();

        foreach (const QString &file, filePaths) {
            qDebug() << "选中文件：" << file;
            QString filelist = QDir::toNativeSeparators(file);
            QFileInfo fileInfo(filelist);
            QString filename = fileInfo.fileName();
            if(_list->find(filename) == _list->end()){
                //说明list中没有该项
                _list->insert(filename);
                _playlistwidget->showlist(filename);
                // todo：更新VLC列表
                _vlcKits->addlist(file);
                qDebug() << "525" << file;
            }
        }
    }
    if(!_playlistwidget->isVisible()){
        if(!this->isFullScreen()){
            //播放列表的显示/隐藏不应该影响左侧布局的大小

            //显示变为隐藏
            resize(width()+_playlistwidget->width(), height());

        }
        _playlistwidget->setVisible(true);
    }

    _btMenuCenter->hide();
}


//通过双击列表项触发播放
void CMainWindow::onPlaylistItemClicked(QListWidgetItem *item)
{
    if (_isplay) {
        _vlcKits->stop();
        _isplay = false;
    }

    bool ret = _vlcKits->play(_playlistwidget->getIndex(item), (void*)_cVideoWidget->winId());

    if (!ret) {
        QMessageBox::warning(this, "错误", "无法播放文件");
    }
    if (ret) {
        _isplay = true;
    } else {
        _isplay = false;
    }

    _playbtn->PlayButton(_isplay);

    //Windows头文件中的定时器函数
    int nret = SetTimer(NULL, 1, 300, TimeProc);
}

void CMainWindow::playIdx(int idx)
{
    if (_isplay) {
        _vlcKits->stop();
        _isplay = false;
    }

    bool ret = _vlcKits->play(idx, (void*)_cVideoWidget->winId());

    if (!ret) {
        QMessageBox::warning(this, "错误", "无法播放文件");
    }
    if (ret) {
        _isplay = true;
    } else {
        _isplay = false;
    }

    _playbtn->PlayButton(_isplay);

    //Windows头文件中的定时器函数
    SetTimer(NULL, 1, 300, TimeProc);
}

void CMainWindow::playNext()
{
    int idx = -1;
    if(_currIdx >= 0){
        idx = _currIdx + 1;
        idx %= _list->size();
        playIdx(idx);
    }else{
        QMessageBox::warning(this, "错误", "当前没有视频");
    }
}

void CMainWindow::playPre()
{
    int idx = -1;
    if(_currIdx >= 0){
        if(_currIdx == 0){
            idx = _list->size() - 1;
        }else{
            idx = _currIdx - 1;
        }
        playIdx(idx);
    }else{
        QMessageBox::warning(this, "错误", "当前没有视频");
    }
}



void CMainWindow::play_pause()
{
    qDebug() << "553---" ;
    if(_currIdx >= 0){
        if(_isplay == false) {
            _vlcKits->play();
            _isplay=true;
        } else{
            _vlcKits->pause();
            _isplay=false;
        }

        _playbtn->PlayButton(_isplay);
    }
}

void CMainWindow::on_btnStop_clicked()
{
    //7.停止播放
    _vlcKits->stop();
    _isplay=false;
    _playbtn->PlayButton(_isplay);
    _cbcb->setCurPlayTime(0);
    _cbcb->setTotalTime(0);
    //_isStopCurr = true;
    //_isStopTotal = true;
}

void CMainWindow::fullScreen()
{
    if(this->isFullScreen()) {
            if(_playlistwidget->isVisible()){
                //resize(width()+_playlistwidget->width(), height());
                _playlistwidget->hide();
            }else{
                this->showNormal();
                resize(1000, 800);

                showWidget();
                _ptitleBar->updateMaxButtonIcon(false);
            }

        } else{
            this->showFullScreen();
            if(_playlistwidget->isVisible()){
                _playlistwidget->hide();
            }
            hideWidget();
            _ptitleBar->updateMaxButtonIcon(true);
        }
}

void CMainWindow::setCurPlayTime(const qint64 &curMs)
{
    _cbcb->setCurPlayTime(curMs);
}

void CMainWindow::setTotalTime(const qint64 &tatalMs)
{
    _cbcb->setTotalTime(tatalMs);
}

void CMainWindow::setTimeSliderValue(int position)
{
    // 更新滑块位置（QSlider的值为整数）
    _hSlider->setValue(static_cast<int>(position));
}
